package top.whysu.rongcloud.service.impl;

import io.rong.RongCloud;
import io.rong.models.response.TokenResult;
import io.rong.models.user.UserModel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import top.whysu.rongcloud.constant.CodeConstant;
import top.whysu.rongcloud.constant.ConfigConstant;
import top.whysu.rongcloud.constant.RongCloudConstant;
import top.whysu.rongcloud.dao.RongCloudUserDao;
import top.whysu.rongcloud.exception.BusinessException;
import top.whysu.rongcloud.po.RongCloudUserPO;
import top.whysu.rongcloud.service.RongCloudUserService;
import top.whysu.rongcloud.util.CheckStringUtil;
import top.whysu.rongcloud.util.RongCloudUtil;

import javax.annotation.Resource;

@Service("RongCloudUserServiceImpl")
public class RongCloudUserServiceImpl implements RongCloudUserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(RongCloudUserServiceImpl.class);

    @Resource
    RongCloudUserDao rongCloudUserDao;

    /**
     * 融云实例
     */
    private RongCloud rongCloud = RongCloud.getInstance(ConfigConstant.appKey, ConfigConstant.appSecret);

    @Override
    public RongCloudUserPO findByAccount(String account) {
        return rongCloudUserDao.selectByAccount(account);
    }

    @Override
    public void updateOrInsertByAccount(RongCloudUserPO newUserPO) {
        if (newUserPO == null) {
            throw new BusinessException(CodeConstant.Http.PARAM_ERROR, "对象不能为空！");
        }
        if (StringUtils.isBlank(newUserPO.getAccount())) {
            throw new BusinessException(CodeConstant.Http.PARAM_ERROR, "账号不能为空！");
        }
        if (StringUtils.isNotBlank(newUserPO.getNickname())) {
            // 昵称最大32字节
            if (newUserPO.getNickname().length() > 32) {
                throw new BusinessException(CodeConstant.Http.PARAM_ERROR, "昵称长度不能超过32字节！");
            }
            // 昵称不能包含emoji表情
            if (CheckStringUtil.containsEmoji(newUserPO.getNickname())) {
                throw new BusinessException(CodeConstant.Http.PARAM_ERROR, "昵称不能包含emoji表情！");
            }
        }
        // 查询账号是否存在
        RongCloudUserPO dbUserPO = rongCloudUserDao.selectByAccount(newUserPO.getAccount());
        if (dbUserPO != null) {
            // 如果昵称更改了，以新的为准
            if (StringUtils.isNotBlank(newUserPO.getNickname()) && !newUserPO.getNickname().equals(dbUserPO.getNickname())) {
                //emoji表情转码
                //userRongCloudPO.setNickname(EmojiParser.parseToAliases(userRongCloudPO.getNickname()));
                dbUserPO.setNickname(newUserPO.getNickname());
            }
            // 如果头像变了，以新的为准
            if (StringUtils.isNotBlank(newUserPO.getAvatar()) && !newUserPO.getAvatar().equals(dbUserPO.getAvatar())) {
                dbUserPO.setAvatar(newUserPO.getAvatar());
            }
            //如果融云token不存在，则重新获取
            if (StringUtils.isBlank(dbUserPO.getToken())) {
                // 注册融云token
                registerToken(dbUserPO.getAccount(), dbUserPO.getNickname(), dbUserPO.getAvatar(), dbUserPO);
                // 更新
                rongCloudUserDao.update(dbUserPO);
            }
        } else {
            // 昵称如果为空，则使用账号
            if (StringUtils.isBlank(newUserPO.getNickname())) {
                newUserPO.setNickname(newUserPO.getAccount());
            }
            newUserPO.setToken("");
            newUserPO.setRongCloudUserId("");
            // 注册融云token
            registerToken(newUserPO.getAccount(), newUserPO.getNickname(), newUserPO.getAvatar(), newUserPO);
            // 新增
            rongCloudUserDao.insert(newUserPO);
        }
    }

    @Override
    public void registerToken(String account, String name, String portrait, RongCloudUserPO rongCloudUserPO) {
        // 用户名（昵称）为空，则使用账号
        if (StringUtils.isBlank(name)) {
            name = account;
        }
        // 头像为空则使用默认头像
        if (StringUtils.isBlank(portrait)) {
            portrait = ConfigConstant.defaultImage;
        }
        try {
            UserModel userModel = new UserModel(account, name, portrait);
            TokenResult result = rongCloud.user.register(userModel);
            if (result.code == RongCloudConstant.Code.SUCCESS) {
                rongCloudUserPO.setToken(result.getToken());
                rongCloudUserPO.setRongCloudUserId(result.getUserId());
            }
        } catch (Exception e) {
            LOGGER.error("注册融云发生异常", e);
        }
    }

}
